import { useState } from 'react'
import { Button, Search, SearchProps } from '@antmjs/vantui'
import { SearchBarProps } from './interface'

import './index.less'

const SearchBar = ({
	onChange,
	showSearchButton,
	searchButtonText = '搜索',
	...rest
}: SearchBarProps) => {
	const [value, setValue] = useState()
	const _onChange: SearchProps['onChange'] = e => {
		setValue(e.detail)
		!showSearchButton && onChange?.(value)
	}
	// 按enter 键会触发两次 内部方法onConfirm 和onChange都触发
	const _onSearch: SearchProps['onSearch'] = e => {
		setValue(e.detail)
		onChange?.(value)
	}

	const handleSearchTextChange = () => {
		onChange?.(value)
	}
	return (
		<Search
			{...rest}
			onChange={_onChange}
			onSearch={_onSearch}
			background='rgba(237, 237, 237, 0.9)'
			renderAction={
				showSearchButton ? (
					<Button
						type='info'
						size='normal'
						className='search-button'
						onClick={handleSearchTextChange}
					>
						{searchButtonText}
					</Button>
				) : undefined
			}
		/>
	)
}

export default SearchBar
